package com.kcht.np.common.domain;

import com.kcht.np.common.exception.ParameterException;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.Arrays;

public class SimpleFile {
    private String fileName;
    private byte[] bytes;

    private SimpleFile(){}
    public static SimpleFile get(byte[] bytes, String fileName){
        if(bytes==null||fileName==null){
            throw new NullPointerException();
        }
        if(!fileName.matches("^[^ ]*\\.[^ ]+$")){
            throw new ParameterException("文件名不能存在空格且需有后缀名");
        }
        SimpleFile response=new SimpleFile();
        response.bytes=bytes;
        response.fileName=fileName;
        return response;
    }


    public static SimpleFile get(InputStream in, String fileName){
        if(in==null||fileName==null){
            throw new NullPointerException();
        }
        if(!fileName.matches("^[^ ]*\\.[^ ]+$")){
            throw new ParameterException("文件名不能存在空格且需有后缀名");
        }
        SimpleFile response=new SimpleFile();
        response.bytes=new byte[1024];
        int data;
        int length=0;
        try{
            while((data=in.read())!=-1) {
                response.bytes[length]=(byte)data;
                length++;
                if(length==response.bytes.length){
                    response.bytes = Arrays.copyOf(response.bytes, length * 2);
                }
            }
            System.out.println(length);
            response.bytes=Arrays.copyOf(response.bytes,length);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        response.fileName=fileName;
        return response;
    }

    public static SimpleFile get(File file){
        if(file==null){
            throw new NullPointerException();
        }
        SimpleFile response=new SimpleFile();
        try {
            response.bytes=FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.fileName=file.getName();
        return response;
    }

    /**
     * 取文件别名
     * */
    public static SimpleFile get(File file, String fileName){
        if(file==null||fileName==null){
            throw new NullPointerException();
        }
        if(!fileName.matches("^[^ ]*\\.[^ ]+$")){
            throw new ParameterException("文件名不能存在空格且需有后缀名");
        }
        SimpleFile response=new SimpleFile();
        try {
            response.bytes=FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.fileName=fileName;
        return response;
    }

    public String getFileName() {
        return fileName;
    }

    public byte[] getBytes() {
        return bytes;
    }
}
